var express = require('express');
var router = express.Router();
var Article = require('../model/index_article');
var editArticle = require('../model/article_list');
var clearHtml = require('../utils/clearHtml');
require('../utils/dateFormat');

// 发布文章
router.post('/send', async (req, res) => {
  let { userId, classifyId, articleId, articleTitle, articleContent, userName, userAvatar } = req.body;
  try {
    if (!userId || !classifyId || !articleId || !articleTitle || !articleContent || !userName || !userAvatar) {
      res.json({
        resultCode: '0002',
        resultMessage: '参数错误',
        result: ''
      })
    } else {
      const exist = await Article.findOne({
        userId,
        classifyId,
        articleId
      })
      if (exist) {
        await Article.updateOne({
          userId,
          classifyId,
          articleId
        },{
          articleTitle,
          articleContent,
          articleText: clearHtml(articleContent)
        })
      } else {
        await Article.insertMany({
          userId,
          classifyId,
          articleId,
          articleTitle,
          articleContent,
          userName,
          userAvatar,
          createTime: new Date().Format('yyyy-MM-dd hh:mm:ss'),
          articleText: clearHtml(articleContent)
        })
      }
      await editArticle.updateOne({
        userId,
        classifyId,
        articleId
      },{
        status: '1'
      })
      res.json({
        resultCode: '0000',
        resultMessage: '发布成功',
        result: ''
      })
    }
  } catch(err) {
    res.json({
      resultCode: '9999',
      resultMessage: err.message,
      result: ''
    })
  }
})

// 请求列表
router.get('/list', async (req, res) => {
  const { page } = req.query
  try { 
      const exist = await Article.find({}).skip(page * 10).limit(10);
      res.json({
        resultCode: '0000',
        resultMessage: '查询成功',
        result: exist
      })
  } catch(err) {
    res.json({
      resultCode: '9999',
      resultMessage: err.message,
      result: ''
    })
  }
})

// 文章详情
router.get('/detail', async (req, res) => {
  const { articleId } = req.query
  try {
    const exist = await Article.findOne({
      articleId
    })
    if (exist) {
      res.json({
        resultCode: '0000',
        resultMessage: '查询成功',
        result: exist
      })
    } else {
      res.json({
        resultCode: '0002',
        resultMessage: '查询错误',
        result: ''
      })
    }
  } catch(err) {
    res.json({
      resultCode: '9999',
      resultMessage: err.message,
      result: ''
    })
  }
})
module.exports = router